package com.zq.im.network;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;


import com.google.gson.Gson;
import com.zq.im.utils.SharePreferenceUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;


public class OKHttpRequest implements IHttpRequest {
    private SPHttpCache mHttpCache;

    Handler mainHandler = new Handler(Looper.getMainLooper());

    public OKHttpRequest() {
        mHttpCache = new SPHttpCache();
    }

    public <T> void get(Context context, String url, Map<String, Object> params,
                        final HttpCallBack<T> callback, final boolean cache) {
        OkHttpClient mOkHttpClient = new OkHttpClient();
        // 公共参数

        final String jointUrl = Utils.jointParams(url, params);  //打印

        Request.Builder requestBuilder = new Request.Builder().url(jointUrl).tag(context)
                .header("Content-Type", "application/json");

        //可以省略，默认是GET请求
        Request request = requestBuilder.build();

        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                // 失败
                mainHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        callback.onFailure(e);
                    }
                });


            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String resultJson = response.body().string();
                final Gson gson = new Gson();
                final T[] objResult = (T[]) new Object[]{null};

                mainHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            objResult[0] = (T) gson.fromJson(resultJson, Utils.analysisClazzInfo(callback));
                        } catch (Exception e) {
//                            AEDException aedException = new AEDException();
//                            aedException.setCode();
                            callback.onFailure(e);
                            return;
                        }
                        callback.onSuccess(objResult[0]);

                    }
                });

            }
        });
    }


    @Override
    public <T> void post(Context context, String url, Map<String, Object> params, final HttpCallBack<T> callback, boolean cache) {

        OkHttpClient mOkHttpClient = new OkHttpClient();
        FormBody.Builder builder = new FormBody.Builder();
        for (String key : params.keySet()) {
            Object value = params.get(key);
            builder.add(key, value.toString());
        }
        RequestBody requestBody = builder.build();
        final String jointUrl = Utils.jointParams(url, params);
        Request.Builder requestBuilder = new Request.Builder().url(url).tag(context)
                .addHeader("content-type", "application/json;charset:utf-8")
                .post(requestBody);


        Request request = requestBuilder.build();

        mOkHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                mainHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (e.toString().contains("Timeout")) {
                            IOException ioException = new IOException("连接超时");
                            callback.onFailure(ioException);
                        } else {
                            IOException ioException = new IOException("连接错误");
                            callback.onFailure(ioException);
                        }
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String resultJson = response.body().string();
                final Gson gson = new Gson();
                final T[] objResult = (T[]) new Object[]{null};
                mainHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            objResult[0] = (T) gson.fromJson(resultJson, Utils.analysisClazzInfo(callback));
                        } catch (Exception e) {
                            IOException ioException = new IOException("解析错误");
                            callback.onFailure(ioException);
                            return;
                        }
                        callback.onSuccess(objResult[0]);
                    }
                });

            }
        });

    }

    @Override
    public <T> void download(Context context, String url, Map<String, Object> params, HttpCallBack<T> callback) {

    }

    @Override
    public <T> void upload(Context context, String url, Map<String, Object> params, final HttpCallBack<T> callback) {
        OkHttpClient client = new OkHttpClient.Builder().build();

        // 文件上传的请求体封装
        MultipartBody.Builder bodyBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM);
        for (String key : params.keySet()) {
            Object value = params.get(key);
            if (value instanceof String) {
                bodyBuilder.addFormDataPart(key, (String) params.get(key));
            }
            if (value instanceof Integer) {
                bodyBuilder.addFormDataPart(key, params.get(key) + "");
            }
            if (value instanceof List) {
                ArrayList<Object> imagesList = (ArrayList) value;
                //注意 接口只接受两张图片
                int count = 2;
                if (imagesList.size() > count) {
                    count = 2;
                } else {
                    count = imagesList.size();
                }
                for (int i = 0; i < count; i++) {
                    Object item = imagesList.get(i);
                    File file = null;
                    if (item instanceof String) {
                        String pathname = (String) item;
                        file = new File(pathname.split(":")[1]);
                    } else if (item instanceof File) {
                        file = (File) item;
                    }
                    long length = file.length();

                    RequestBody requestBody = RequestBody.create(MediaType.parse("image/jpg"), file);
                    bodyBuilder.addFormDataPart("file" + (i + 1), file.getName(), requestBody);
                }
            } else {

            }
        }
        MultipartBody multipartBody = bodyBuilder.build();

        Request.Builder builder = new Request.Builder()
                .url(url)
                .header("Content-Type", "multipart/form-data")
                .post(multipartBody);

        String session = SharePreferenceUtils.getString("session");
        builder.header("Cookie", "JSESSIONID=" + session);

        Request request = builder.build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, final IOException e) {
                mainHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        if (e.toString().contains("Timeout")) {
                            IOException ioException = new IOException("连接超时");
                            callback.onFailure(ioException);
                        } else {
                            IOException ioException = new IOException("连接错误");
                            callback.onFailure(ioException);
                        }
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String resultJson = response.body().string();
                final Gson gson = new Gson();
                final T[] objResult = (T[]) new Object[]{null};
                mainHandler.post(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            objResult[0] = (T) gson.fromJson(resultJson, Utils.analysisClazzInfo(callback));
                        } catch (Exception e) {
                            IOException ioException = new IOException("解析错误");
                            callback.onFailure(ioException);
                            return;
                        }
                        callback.onSuccess(objResult[0]);
                    }
                });


            }
        });


    }
}
